package leetcode.题库.二叉树;

import leetcode.题库.pubclass.TreeNode;

/**
 * description:从前序与中序遍历序列构造二叉树
 *
 * @author 颜真明
 * @date 2024/4/1  11:21
 */
public class Solution105 {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder.length == 0) {
            return null;
        }
        return buildTree(preorder, 0, preorder.length-1, inorder, 0, inorder.length-1);
    }

    public TreeNode buildTree(int[] preorder, int preL, int preR, int[] inorder, int inL, int inR){
        int preLen = preorder.length;
        int inLen = inorder.length;
        if (preL > preR || inL > inR || preL < 0 || preL >= preLen || inL < 0 || inL >= inLen) {
            return null;
        }
        int rootVal = preorder[preL];
        int mid = preL;
        for (int i = inL; i <= inR; i++) {
            if (inorder[i] == rootVal) {
                mid = i;
                break;
            }
        }
        TreeNode root = new TreeNode(rootVal);
        root.left = buildTree(preorder, preL+1, mid-inL+preL, inorder, inL, mid-1);
        root.right = buildTree(preorder, mid-inL+preL+1, preR, inorder, mid+1, inR);
        return root;
    }
}
